import OpenAI from "openai";
import * as vscode from "vscode";
import axios from "axios";
export class HarmonyPilotGUIWebviewViewProvider implements vscode.WebviewViewProvider {
    private webView?: vscode.WebviewView;
    constructor(private readonly _extensionUri: vscode.Uri , private context:vscode.ExtensionContext) {

    }

    resolveWebviewView(webviewView: vscode.WebviewView) {
        const deepseek = new OpenAI({  
            baseURL: 'https://api.deepseek.com/v1',  
            apiKey: 'sk-37addc2257584318ba5e300d38da7305', 
            dangerouslyAllowBrowser: true
          }); 
        webviewView.webview.options = {
            // 在 webview 允许脚本
            enableScripts: true,
            localResourceRoots: [this._extensionUri],
          };
        //webviewView.webview.html = this.getHtmlForWebview(webviewView.webview);
        webviewView.webview.html = this.getDebugHtml();
        webviewView.webview.onDidReceiveMessage(async (message) => {
            switch (message.type) {
              case 'queryDeepseek':
                try {
                  const response = await deepseek.chat.completions.create({
                    messages: [{ role: 'user', content: message.data }],
                    model: 'deepseek-chat',
                  });
                  console.log(response.choices[0].message.content);
                  webviewView.webview.postMessage({
                    type: 'response',
                    data: response.choices[0].message.content
                  });
                } catch (error) {
                  webviewView.webview.postMessage({
                    type: 'error',
                    data: `API Error: ${error.message}`
                  });
                }
                break;
            }
          }, undefined, this.context.subscriptions);
    }
    getHtmlForWebview(webview: vscode.Webview) {
        return `
        <!DOCTYPE html>
        <html>
            <head>
                <title>HarmonyPilot</title>
            </head>
            <body>
                <h1>HarmonyPilot</h1>
            </body>
        </html>`;
    }

    getDebugHtml() {
        return `
        <!DOCTYPE html>
        <html>
            <head>
                <title>HarmonyPilot</title>
                <link rel="stylesheet" href="http://localhost:5174/node_modules/@devui-design/icons/icomoon/devui-icon.css">
                <link rel="stylesheet" href="http://localhost:5174/src/style.css">
            </head>
            <body>
                <div id="app"></div>
                <script type="module" src="http://localhost:5174/src/main.ts"></script>
                <script>
                window.staticPath = "http://localhost:5174/";
                window.vscode = acquireVsCodeApi && acquireVsCodeApi();
                </script>
            </body>
        </html>`;
    }
        
}
